package com.dhl.cloud.common.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;


/**
 * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    
    private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
        "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };

    public static List<String> getBetweenDates(String starttime, String endtime,SimpleDateFormat parseFormatter,SimpleDateFormat formatFormatter) {
        try {
            List<String> result = new ArrayList<>();
            Calendar tempStart = Calendar.getInstance();
            Date start = parseFormatter.parse(starttime);
            tempStart.setTime(start);
            tempStart.add(Calendar.DAY_OF_YEAR, 0);

            Calendar tempEnd = Calendar.getInstance();
            Date end = parseFormatter.parse(endtime);
            tempEnd.setTime(end);
            while (tempStart.before(tempEnd)) {
                result.add(formatFormatter.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
            return result;
        }catch (Exception e){

        }
        return null;

    }
    
    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd）
     */
    public static String getDate() {
        return getDate("yyyy-MM-dd");
    }
    
    public static String getDayNameOfWeek(String dateStr){
    	if(dateStr == null) return "";
    	Date date = parseDate(dateStr);
    	return getDayNameOfWeek(date);
    }
    public static String getDayNameOfWeek(Date date){
        if(null == date) return null;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        return formatDate(date, "E");
    }
    
    /**
     * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }
    
    /**
     * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
     */
    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }
    
    /**
     * 得到日期时间字符串，转换格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String formatDateTime(Date date) {
        if(null == date) return "";
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前时间字符串 格式（HH:mm:ss）
     */
    public static String getTime() {
        return formatDate(new Date(), "HH:mm:ss");
    }

    /**
     * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
     */
    public static String getDateTime() {
        return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 得到当前年份字符串 格式（yyyy）
     */
    public static String getYear() {
        return formatDate(new Date(), "yyyy");
    }

    /**
     * 得到当前月份字符串 格式（MM）
     */
    public static String getMonth() {
        return formatDate(new Date(), "MM");
    }

    /**
     * 得到当天字符串 格式（dd）
     */
    public static String getDay() {
        return formatDate(new Date(), "dd");
    }

    /**
     * 得到当前星期字符串 格式（E）星期几
     */
    public static String getWeek() {
        return formatDate(new Date(), "E");
    }
    
    /**
     * 日期型字符串转化为日期 格式
     * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", 
     *   "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
     */
    public static Date parseDate(Object str) {
        if (str == null){
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取过去的天数
     * @param date
     * @return
     */
    public static long pastDays(Date date) {
        long t = new Date().getTime()-date.getTime();
        return t/(24*60*60*1000);
    }
    
    
    public static Date getDateStart(Date date) {
        if(date==null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date= sdf.parse(formatDate(date, "yyyy-MM-dd")+" 00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    
    public static Date getDateEnd(Date date) {
        if(date==null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date= sdf.parse(formatDate(date, "yyyy-MM-dd") +" 23:59:59");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    
    /**
     * 判断字符串是否是日期
     * @param timeString
     * @return
     */
    public static boolean isDate(String timeString){
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        try{
            format.parse(timeString);
        }catch(Exception e){
            return false;
        }
        return true;
    }
    
    /**
     * 格式化时间
     * @param timestamp
     * @return
     */
    public static String dateFormat(Date timestamp){
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(timestamp);
    }
    
    /**
     * 获取系统时间Timestamp
     * @return
     */
    public static Timestamp getSysTimestamp(){
        return new Timestamp(new Date().getTime());
    }
    
    /**
     * 获取系统时间Date
     * @return
     */
    public static Date getSysDate(){
        return new Date();
    }
    
    /**
     * 生成时间随机数 
     * @return
     */
    public static String getDateRandom(){
        String s=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        return s;
    }

    /**
     * 得到当前日期和时间字符串 格式（yyyyMMddHHmmss）
     * @author 宋永刚
     *
     * @return
     *
     * 修改日期：2016-8-1
     */
    public static String getDateTimePlain() {
        return formatDate(new Date(), "yyyyMMddHHmmss");
    }

    public static String getMillDateTimePlain(){
        return formatDate(new Date(), "yyyyMMddHHmmssSSS");
    }

    /**
     * 计算两个日期相差分钟数
     * @param startDate
     * @param endDate
     * @return
     */
    public static long getDistanceMin(Date startDate, Date endDate) {
        if(startDate == null || endDate == null) return 0;
        long start = startDate.getTime();
        long end = endDate.getTime();
        long diff = 0;
        if(start < end){
            diff = end - start;
        } else {
            diff = start - end;
        }
        long mins = diff / 60000;
        return mins;
    }

    /**
     * 获取指定日期所在周的星期一的日期对象
     * @param date
     * @return
     */
    public static Date getThisWeekMonday(Date date) {
        if(null == date) return null;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        return cal.getTime();
    }

    /**
     * 获取天时分秒倒计时
     * @param ms
     * @return
     */
    public static String getDayHourMinuteSecond(long ms) {
        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;
        long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        String strDay = day < 10 ? "0" + day : "" + day; //天
        String strHour = hour < 10 ? "0" + hour : "" + hour;//小时
        String strMinute = minute < 10 ? "0" + minute : "" + minute;//分钟
        String strSecond = second < 10 ? "0" + second : "" + second;//秒
        String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;//毫秒
        strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;

        return strDay + "天" + strHour + "时" + strMinute + "分钟" + strSecond + "秒";

    }

    /**
     * 获取明日凌晨距现在时间的秒差
     *
     * @return
     */
    public static long getTomorrowMorningToNowTime() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        long tomorrowToNow=(c.getTimeInMillis()-System.currentTimeMillis())/1000;
        return tomorrowToNow;
    }
    
    public static int compDate(String str){
    	try
    	{
    		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        	Date date = new Date();
        	return date.compareTo(sd.parse(str));
    	}
    	catch(Exception e)
    	{
    		return -2;
    	}
    }

    
    public static int compDateHM(String starttime,String endtime){
    	try
    	{
    		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        	return sd.parse(starttime).compareTo(sd.parse(endtime));
    	}
    	catch(Exception e)
    	{
    		return -2;
    	}
    }
    
    public static int compDate(String starttime,String endtime){
    	try
    	{
    		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        	return sd.parse(starttime).compareTo(sd.parse(endtime));
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    		return -2;
    	}
    }
    
    public static String addDateMinut(String day, int hour){   
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;   
        try {   
            date = format.parse(day);   
        } catch (Exception ex) {   
            ex.printStackTrace();   
        }   
        if (date == null)   
            return "";   
//        System.out.println("front:" + format.format(date)); //显示输入的日期  
        Calendar cal = Calendar.getInstance();   
        cal.setTime(date);   
        cal.add(Calendar.HOUR, hour);// 24小时制   
        date = cal.getTime();   
//        System.out.println("after:" + format.format(date));  //显示更新后的日期 
        cal = null;   
        return format.format(date);   

    }

    public static String addDateDay(String time, int day){
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = parseDate(time);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (date == null)
            return "";
//        System.out.println("front:" + format.format(date)); //显示输入的日期
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, day);// 24小时制
        date = cal.getTime();
//        System.out.println("after:" + format.format(date));  //显示更新后的日期
        cal = null;
        return formatDateTime(date);

    }
    
    public static Date dateRoll(Date date, int i, int d) {
        // 获取Calendar对象并以传进来的时间为准
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 将现在的时间滚动固定时长,转换为Date类型赋值
        calendar.add(i, d);
        // 转换为Date类型再赋值
        date = calendar.getTime();
        return date;
    }
    
    public static String getCron(Date  date){  
        String dateFormat="ss mm HH dd MM ? yyyy";  
        return  fmtDateToStr(date, dateFormat);  
    }  
    public static Date getCronToDate(String cron) {  
        String dateFormat="ss mm HH dd MM ? yyyy";  
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);  
        Date date = null;  
        try {  
            date = sdf.parse(cron);  
        } catch (Exception e) {  
            return null;
        }  
        return date;  
    }  
    
    public static String fmtDateToStr(Date date, String dtFormat) {  
        if (date == null)  
            return "";  
        try {  
            SimpleDateFormat dateFormat = new SimpleDateFormat(dtFormat);  
            return dateFormat.format(date);  
        } catch (Exception e) {  
            e.printStackTrace();  
            return "";  
        }  
    }

    //Date类型转Calendar类型
    public static Calendar dataToCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    //获取当前时间之后日期
    public static String getAfterTimeByHour(int hour) {

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + hour);

        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());

    }

    //获取当前时间之后日期
    public static String getAfterTimeByDay(double day) {
        double hour = day * 24;

        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + (int)hour);

        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());

    }

    //日期和当前时间比较
    public static boolean compareTime(String time) throws ParseException
    {
        try{
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //将字符串形式的时间转化为Date类型的时间
            Date a=sdf.parse(time);
            //Date类的一个方法，如果当前时间早于a返回true，否则返回false
            if(new Date().before(a)){
                return true;
            }
        }catch (ParseException pe){

        }
        return false;
    }

    public static String convertDate(String createTime) {
        StringBuffer sb = new StringBuffer();
        String createDate = null;
        try{
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date date = df.parse(createTime);
            long differenceValue = new Date().getTime() - date.getTime();
            if(differenceValue < 3600000){
                createDate = (differenceValue / 1000 / 60 ) + "分钟前";
            }else if(differenceValue > 3600000){
                if(differenceValue < 86400000){
                    createDate = (differenceValue / 1000 / 60 / 60 ) + "小时前";
                }else{
                    createDate = createTime;
                }
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return createDate;
    }

    public static String getTime(Date startTime,Date endTime){
        long diff = endTime.getTime() - startTime.getTime();//这样得到的差值是微秒级
        long hours = diff/(1000* 60 * 60); //获取时
        long minutes = (diff-hours*1000*60*60)/(1000*60);  //获取分钟
        long s=(diff/1000-hours*60*60-minutes*60);//获取秒
        String CountTime;
        if (hours==0 && minutes==0){
            CountTime=s+"秒";
        }else if (hours==0 && minutes!=0){
            CountTime=minutes+"分"+s+"秒";
        }else {
            CountTime=hours+"小时"+minutes+"分"+s+"秒";
        }
        return CountTime;
    }

//    //获取时间差方法
//    public static String getTime(Date currentTime,Date firstTime){
//        long diff = currentTime.getTime() - firstTime.getTime();//这样得到的差值是微秒级别
//        //Calendar  currentTimes =dataToCalendar(currentTime);//当前系统时间转Calendar类型
//        //Calendar  firstTimes =dataToCalendar(firstTime);//查询的数据时间转Calendar类型
//        /*int year = currentTimes.get(Calendar.YEAR) - firstTimes.get(Calendar.YEAR);//获取年
//        int month = currentTimes.get(Calendar.MONTH) - firstTimes.get(Calendar.MONTH);
//        int day = currentTimes.get(Calendar.DAY_OF_MONTH) - firstTimes.get(Calendar.DAY_OF_MONTH);*/
//        /*if (day < 0) {
//            month -= 1;
//            currentTimes.add(Calendar.MONTH, -1);
//            day = day + currentTimes.getActualMaximum(Calendar.DAY_OF_MONTH);//获取日
//        }
//        if (month < 0) {
//            month = (month + 12) % 12;//获取月
//            year--;
//        }*/
//        long days = diff / (1000 * 60 * 60 * 24);
//        long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60); //获取时
//        long minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);  //获取分钟
//        long s=(diff/1000-days*24*60*60-hours*60*60-minutes*60);//获取秒
//        //String CountTime=""+"year"+"年"+month+"月"+day+"天"+hours+"小时"+minutes+"分"+s+"秒";
//        String CountTime=hours+"时"+minutes+"分"+s+"秒";
//        return CountTime;
//    }
    
    public static String getTime(Long time){
        long hours = time/(1000* 60 * 60); //获取时
        long minutes = (time-hours*1000*60*60)/(1000*60);  //获取分钟
        long s=(time/1000-hours*60*60-minutes*60);//获取秒
        String CountTime;
        if (hours==0 && minutes==0){
            CountTime=s+"秒";
        }else if (hours==0 && minutes!=0){
            CountTime=minutes+"分"+s+"秒";
        }else {
            CountTime=hours+"小时"+minutes+"分"+s+"秒";
        }
        return CountTime;
    }

    public static List<String> getBetweenDatesWithEndtime(String starttime, String endtime, SimpleDateFormat parseFormatter, SimpleDateFormat formatFormatter) {
        try {
            List<String> result = new ArrayList();
            Calendar tempStart = Calendar.getInstance();
            Date start = parseFormatter.parse(starttime);
            tempStart.setTime(start);
            tempStart.add(6, 0);
            Calendar tempEnd = Calendar.getInstance();
            Date end = parseFormatter.parse(endtime);
            tempEnd.setTime(end);

            while(tempStart.before(tempEnd)||tempStart.equals(tempEnd)) {
                result.add(formatFormatter.format(tempStart.getTime()));
                tempStart.add(6, 1);
            }

            return result;
        } catch (Exception var9) {
            return null;
        }
    }

    public static String addDateMinutes(String day, int minute,SimpleDateFormat parseFormat,SimpleDateFormat formatFormat) {
        Date date = null;

        try {
            date = parseFormat.parse(day);
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        if (date == null) {
            return "";
        } else {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.MINUTE, minute);
            date = cal.getTime();
            cal = null;
            return formatFormat.format(date);
        }
    }

    public static String addDays(String day,Integer addDays){
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(sf.parse(day));
            c.add(Calendar.DAY_OF_MONTH, addDays);
            return sf.format(c.getTime());
        }catch (Exception e){

        }
        return null;
    }
    
	public static String timeTostrHMS(Date date) {
		String strDate = "";
		if (date != null) {
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			strDate = format.format(date);
		}
		return strDate;
	}
	
//    public static void main(String args[]){
//        try{
//        //boolean flag = compareTime( "2020-04-24 12:00:00");
//            System.out.println(addDateDay("2020-04-31 10:00:00",-1));
//    }catch (Exception e){
//        }
//    }

}
